import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { AbstractControl } from '@angular/forms';
import { FormDefaultComponent } from '../basic-form-control/FormDefault.component';

@Component({
    selector: 'app-form-phone-mobile-input',
    templateUrl: './FormInputPhoneMobile.component.html',
})
export class FormInputPhoneMobileComponent extends FormDefaultComponent implements OnInit, OnDestroy {
    @Input() phoneControlId: string;
    @Input() mobileControlId: string;
    phoneRequired = true;
    mobileRequired = true;
    mobileControl: AbstractControl;
    phoneControl: AbstractControl;
    subscriptions = [];

    constructor() {
        super();
    }

    ngOnInit() {
        const { formGroupReference } = this.configuration;
        this.mobileControl = formGroupReference.get(this.mobileControlId);
        let subscription = this.mobileControl.valueChanges.subscribe((mobile) => {
            this.phoneRequired = mobile === '';
            this.mobileRequired = this.phoneControl.value === '';
        });
        this.subscriptions.push(subscription);
        this.phoneControl = formGroupReference.get(this.phoneControlId);
        subscription = this.phoneControl.valueChanges.subscribe((phone) => {
            this.mobileRequired = phone === '';
            this.phoneRequired = this.mobileControl.value === '';
        });
        this.subscriptions.push(subscription);

        this.phoneRequired = !this.mobileControl.value;
        this.mobileRequired = !this.phoneControl.value;
    }

    ngOnDestroy() {
        this.subscriptions.forEach((subscription) => {
            subscription.unsubscribe();
        });
    }

    getFormAttributes(formControlId: string) {
        const attributes = { ...this.configuration, ...{ formControlId } };
        delete attributes.required;
        return attributes;
    }
}
